package com.platform.hjt.base.costant;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationObjectSupport;

public class ApplicationScopeCostantLoader extends WebApplicationObjectSupport{
	
	
	private static final Logger logger = Logger.getLogger(ApplicationScopeCostantLoader.class);  
    
    /** constant classes which can be injected by spring */  
    private Map<String, String> constantClass;  
  
    protected void initApplicationContext() {  
        try {  
            //build constants and put it to the application scope  
            this.buildConstants();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
      
    /** 
     * build constants map 
     *  
     * @return constants map 
     * @throws ClassNotFoundException  
     */  
    private void buildConstants() throws ClassNotFoundException{  
        Map<String, Object> result = new HashMap<String, Object>();  
        for(Map.Entry<String, String> map: constantClass.entrySet()){  
            //the constant group name  
            String k = map.getKey();  
            //the class  
            String v = map.getValue();  
            Class<?> clazz = this.getClass().getClassLoader().loadClass(v);  
            Field[] fields = clazz.getDeclaredFields();  
            for (int i = 0; i < fields.length; i++) {  
                Field field = fields[i];  
                int modifier = field.getModifiers();  
                //must be final & public  
                if (Modifier.isFinal(modifier) && !Modifier.isPrivate(modifier))  
                    try {  
                        String name = field.getName();  
                        Object value = field.get(this);  
                        
                        logger.debug(MessageFormat.format("building constants{0}: name={1},value={2}", new Object[]{k, name,value}));  
                        result.put(name, value);  
                    } catch (IllegalAccessException e) {  
                    }  
            }  
            
            logger.info(MessageFormat.format("put constant [{0}] to application scope.", k));  
            this.getServletContext().setAttribute(k, result);  
        }  
    }  
  
    public Map<String, String> getConstantClass() {  
        return constantClass;  
    }  
  
    public void setConstantClass(Map<String, String> constantClass) {  
        this.constantClass = constantClass;  
    }  
}
